<template>
  <div class="rental-approval-container">
    <el-card class="approval-card">
      <!-- 顶部筛选区域 -->
      <div class="filter-bar">
        <el-input
            v-model="searchParams.companyName"
            placeholder="搜索公司名称"
            clearable
            style="width: 300px"
        >
          <template #prefix>
            <el-icon>
              <search/>
            </el-icon>
          </template>
        </el-input>

        <el-select
            v-model="searchParams.status"
            placeholder="申请状态"
            clearable
            style="width: 150px; margin-left: 10px"
        >
          <el-option label="待审核" value="1"/>
          <el-option label="已通过" value="2"/>
          <el-option label="已拒绝" value="3"/>
          <el-option label="已签约" value="4"/>
        </el-select>

        <el-select
            v-model="searchParams.zoneId"
            placeholder="园区区域"
            clearable
            style="width: 150px; margin-left: 10px"
        >
          <el-option label="A区" value="1"/>
          <el-option label="B区" value="2"/>
          <el-option label="C区" value="3"/>
          <el-option label="D区" value="4"/>
        </el-select>


        <el-button
            type="primary"
            @click="applyFilters"
            style="margin-left: 10px"
        >
          筛选
        </el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>

      <!-- 申请列表表格 -->
      <el-table
          :data="tableData"
          style="width: 100%"
          border
      >
        <el-table-column prop="applicationId" label="申请编号" width="180" fixed/>
        <el-table-column label="公司名称" width="200">
          <template #default="scope">
            {{ scope.row.companyInfo?.companyName || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="企业人数" width="120" align="center">
          <template #default="scope">
            {{ scope.row.companyInfo?.personNumber || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="联系人" width="120">
          <template #default="scope">
            {{ scope.row.companyInfo?.personName || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="联系电话" width="150">
          <template #default="scope">
            {{ scope.row.companyInfo?.personPhone || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="联系邮箱" width="120">
          <template #default="scope">
            {{ scope.row.companyInfo?.personEmail || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="申请园区区域" width="120">
          <template #default="scope">
            <el-tag> {{
                scope.row.smallzoneInfo
                    ? `${['', 'A', 'B', 'C', 'D'][scope.row.smallzoneInfo.zoneId] || '无'}区${scope.row.smallzoneInfo.unitName || '无'}`
                    : '无园区信息'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="spaceArea" label="申请面积(m²)" width="120" align="right">
          <template #default="scope">
            {{ scope.row.spaceArea || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="月租金" width="150" align="right">
          <template #default="scope ">
            ￥{{ scope.row.monthlyRent?.toLocaleString() || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="租赁期限(月)" width="150" align="right">
          <template #default="scope">
            {{ scope.row.rentTime || '0' }}
          </template>
        </el-table-column>
        <el-table-column label="注册资本" width="120" align="right">
          <template #default="scope">
            {{ scope.row.registerCapital || '0' }}
          </template>
        </el-table-column>
        <el-table-column label="成立时间" width="150" align="right">
          <template #default="scope">
            {{ formatDate(scope.row.establishDate) || '无' }}
          </template>
        </el-table-column>
        <el-table-column label="年度营收" width="120" align="right">
          <template #default="scope">
            {{ scope.row.annualRevenue || '0' }}
          </template>
        </el-table-column>
        <el-table-column label="年度税收" width="120" align="right">
          <template #default="scope">
            {{ scope.row.annualTax || '0' }}
          </template>
        </el-table-column>
        <el-table-column label="年度利润" width="120" align="right">
          <template #default="scope">
            {{ scope.row.annualProfit || '0' }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="120" fixed="right">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="详情汇总" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" plain type="primary" @click="viewDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </el-card>

    <!-- 申请详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="`合同文件预览 - ${currentApplication?.applicationId || ''}`"
        width="80%"
        :fullscreen="false"
        height="90vh"
    >
      <div class="file-previewer">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="error">
          <p>{{ errorMessage }}</p>
        </div>

        <!-- PDF预览区域 -->
        <div
            v-show="!loading && !error"
            class="pdf-container"
            style="background: #fafafa; display: none;"
        >
          <!-- 工具栏：保留 isPdf 条件，非PDF时不显示工具栏 -->
          <div class="toolbar" v-if="isPdf">
            <h3>{{ currentApplication?.companyFiles.fileName ?? '合同' }}</h3>
            <div class="controls">
              <el-button @click="zoomOut" :disabled="scale <= 0.5" type="primary">缩小</el-button>
              <span>{{ Math.round(scale * 100) }}%</span>
              <el-button @click="zoomIn" :disabled="scale >= 1" type="primary">放大</el-button>
              <el-button @click="downloadFile" type="primary">下载</el-button>
            </div>
          </div>

          <!-- PDF内容区域：始终渲染Canvas，非PDF时隐藏 -->
          <div class="pdf-content" v-if="isPdf">
            <canvas ref="pdfCanvas"></canvas>
          </div>

          <!-- 非PDF文件提示：移到外面，独立显示 -->
          <div v-if="!isPdf && !loading && !error" class="non-pdf">
            <p>不支持的文件类型，请下载查看</p>
            <el-button @click="downloadFile" type="primary">下载文件</el-button>
          </div>
        </div>
      </div>


      <!-- 右下角的通过按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button
            type="primary"
            @click="handleApprove"
            :disabled="!currentApplication || currentApplication.status !== 1"
            :loading="loadingDialog.approve">
          通过申请
        </el-button>
        <el-button
            type="danger"
            @click="handleReject"
            :disabled="!currentApplication || currentApplication.status !== 1"
            :loading="loadingDialog.reject"
        >
          拒绝申请
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
        v-model="ReviewDialogVisible"
        title="审核意见"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="approvalForm"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          size="default"
      >
        <el-form-item label="审核意见" prop="reviewComment">
          <el-input
              v-model="approvalForm.reviewComment"
              placeholder="请输入审核意见（至少5个字符）"
              autocomplete="off"
              type="textarea"
              rows="4"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ReviewDialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="handleReturn"
              :loading="loadingDialog.submit"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, watch, computed, onMounted, reactive, nextTick} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search} from '@element-plus/icons-vue'
import {getList, updateList} from "@/api/application.js";
import * as pdfjsLib from 'pdfjs-dist';
// // 配置pdf.js
// pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
//     'pdfjs-dist/build/pdf.worker.min.js',
//     import.meta.url
// ).href;

// 5.x 版本：通过 URL 直接获取 worker 文件路径（无需导入默认值）
const workerUrl = new URL(
    'pdfjs-dist/build/pdf.worker.mjs',
    import.meta.url
).href;

// 配置 Worker 路径
pdfjsLib.GlobalWorkerOptions.workerSrc = workerUrl;
console.log('pdfjsLib 核心库版本:', pdfjsLib.version);

// 申请数据
const applications = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(50)
const total = ref(10)
const selectedApplications = ref([])

// 筛选条件
const searchParams = reactive({
  companyName: null,
  status: undefined,
  zoneId: undefined
})

// 对话框状态
const detailDialogVisible = ref(false)
const currentApplication = ref(null)
const ReviewDialogVisible = ref(false)
const approvalForm = ref({
  applicationId: 0,
  reviewComment: '',
  status: 0
})
const formRef = ref(null)
const loadingDialog = reactive({
  approve: false,
  reject: false,
  submit: false
})
const actionType = ref('') // 'approve' 或 'reject'


//表单规则
const rules = reactive({
  reviewComment: [ // 与 el-form-item 的 prop 一致
    {required: true, message: '请输入审核意见', trigger: 'blur'},
    {min: 5, message: '意见长度至少为5个字符', trigger: 'blur'}
  ]
})

// 表格数据
const tableData = ref([])
onMounted(() => {
  fetchApplicationList(); // 初始化时调用接口
});

//pdf预览--状态管理
const error = ref(false);
const errorMessage = ref('');
const isPdf = ref(false);
let pdfDoc = "";
const scale = ref(0.7);
const canvasRefs = ref({});
let pdfBlobUrl = '';
const pdfCanvas = ref();
const isRendering = ref(false); // 新增：标记是否正在渲染

/**
 * 获取申请列表数据
 */
const fetchApplicationList = async () => {
  try {
    const params = reactive({
      page: currentPage.value,
      pageSize: pageSize.value,
      companyName: searchParams.companyName,
      status: searchParams.status,
      zoneId: searchParams.zoneId
    })
    const res = await getList(params)
    if (!res || !res.data || !Array.isArray(res.data.records)) {
      throw new Error('API返回格式异常: 缺少必要的数据字段')
    }
    tableData.value = res.data.records //列表所有数据
    total.value = res.data.total
  } catch (error) {
    console.error('加载申请列表失败:', error)
    ElMessage.error(error.message || '数据加载失败')
  }
}
fetchApplicationList()

/**
 打回申请审核
 */
const handleReturn = async () => {
  try {
    if (!currentApplication.value?.applicationId) {
      ElMessage.error('申请ID不存在，无法提交');
      return;
    }

    approvalForm.value.reviewComment = approvalForm.value.reviewComment.trim();
    approvalForm.value.applicationId = currentApplication.value.applicationId
    approvalForm.value.status = actionType.value === 'approve' ? 2 : 3;

    const isValid = await new Promise((resolve) => {
      formRef.value.validate((valid) => {
        resolve(valid)
      })
    })
    if (!isValid) {
      ElMessage.warning('验证失败')
      return
    }

    // 验证通过后再组装数据
    const formData = {
      applicationId: approvalForm.value.applicationId,
      reviewComment: approvalForm.value.reviewComment,
      status: approvalForm.value.status,
    };

    loadingDialog.submit = true;

    // 执行打回操作
    const result = await updateList(formData)
    if (result.code === 200) {
      ElMessage.success(`${actionType.value === 'approve' ? '通过' : '拒绝'}申请成功`);
      approvalForm.value.reviewComment = '';
      ReviewDialogVisible.value = false;
      detailDialogVisible.value = false;
      // 刷新列表数据
      await fetchApplicationList();
    } else {
      ElMessage.error(result.message || `${actionType.value === 'approve' ? '通过' : '拒绝'}申请失败`);
    }
  } catch (error) {
    console.error('提交审核意见失败:', error);
    // 表单验证失败不显示错误提示，Element会自动处理
    if (error.name !== 'ValidationError') {
      ElMessage.error('提交失败，请重试');
    }
  } finally {
    loadingDialog.submit = false;
  }
}


// 操作

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString);
  if (isNaN(date.getTime())) {
    return '';
  }
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',  // 月：中文全称（如“08月”，而非“8月”）
    day: '2-digit'
  });
};

// 获取状态标签
const getStatusLabel = (status) => {
  const labels = {
    1: '待审核',
    2: '已通过',
    3: '已拒绝',
    4: '已签约'
  }
  return labels[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    1: 'warning',
    2: 'success',
    3: 'danger',
    4: 'primary'
  }
  return types[status] || ''
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchApplicationList()
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchApplicationList()
}

// 应用筛选
const applyFilters = () => {
  currentPage.value = 1
  fetchApplicationList()
}

//通过申请
const handleApprove = () => {
  if (!currentApplication.value) return
  approvalForm.reviewComment = ''
  actionType.value = "approve"
  // 显示审核意见对话框
  nextTick(() => {
    ReviewDialogVisible.value = true
  })
}

// 处理拒绝申请
const handleReject = () => {
  if (!currentApplication.value) return
  approvalForm.reviewComment = ''
  actionType.value = "reject"

  // 显示审核意见对话框
  nextTick(() => {
    ReviewDialogVisible.value = true
  })
}


// 重置筛选
const resetFilters = () => {
  searchParams.companyName = undefined
  searchParams.status = undefined
  searchParams.zoneId = undefined
  currentPage.value = 1
  fetchApplicationList()
}

// 查看申请详情
const viewDetails = (application) => {
  currentApplication.value = {...application};
  // approvalForm.value.comment = '';
  detailDialogVisible.value = true;

  // 提前判断文件是否为PDF
  const fileUrl = currentApplication.value?.companyFiles.fileUrl || '';
  isPdf.value = checkFileIsPdf(fileUrl);

  // 使用nextTick确保DOM更新
  nextTick(() => {
    if (isPdf.value) {
      loadFile();
    }
  });
};

// 检查文件是否为PDF
const checkFileIsPdf = (fileUrl) => {
  return fileUrl.toLowerCase().endsWith('.pdf');
};

// 加载文件
const loadFile = async () => {
  console.log('=== loadFile 开始执行 ==='); // 新增日志

  const fileUrl = currentApplication.value?.companyFiles.fileUrl;
  const fileName = currentApplication.value?.companyFiles.fileName;

  if (!fileUrl) {
    error.value = true;
    errorMessage.value = '文件地址不存在';
    console.error(errorMessage);
    return;
  }

  // 等待DOM更新，再检查Canvas （挂载成功）
  await nextTick();
  if (!pdfCanvas.value) {
    error.value = true;
    errorMessage.value = 'Canvas元素未找到，无法渲染';
    console.error('pdfCanvas.value 为 null，DOM未挂载');
    return;
  }

  loading.value = true;
  error.value = false;
  isPdf.value = checkFileIsPdf(fileUrl);

  if (!isPdf.value) {
    loading.value = false;
    return;
  }

  try {
    const requestUrl = `${fileUrl}?t=${Date.now()}`;  // 加时间戳防缓存

    const pdfResponse = await fetch(requestUrl, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`  // 如有需要携带权限
      }
    });

    if (!pdfResponse.ok) {
      throw new Error(`文件请求失败，状态码: ${pdfResponse.status}`);
    }

    //返回pdf文件blob二进制流
    const pdfBlob = await pdfResponse.blob();
    const pdfBlobUrl = URL.createObjectURL(pdfBlob);

    // 加载并渲染PDF（后续逻辑不变）
    const loadingTask = pdfjsLib.getDocument(pdfBlobUrl);
    pdfDoc = await loadingTask.promise;

    if (!pdfDoc || typeof pdfDoc.getPage !== 'function') {
      throw new Error('获取的不是有效的 PDF 文档实例');
    }

    await nextTick();
    if (pdfCanvas.value) {
      canvasRefs.value[1] = pdfCanvas.value;
      console.log('Canvas手动绑定成功：', canvasRefs.value[1]);
    } else {
      throw new Error('Canvas元素未找到，DOM挂载失败');
    }
    await renderPage(1);


  } catch (err) {
    error.value = true;
    errorMessage.value = `加载失败: ${err.message}`;
    console.error('PDF加载错误:', err);
  } finally {
    loading.value = false;
  }
};

// 3. 渲染指定页（renderPage）：仅处理第1页
const renderPage = async (pageNum) => {
  // 如果正在渲染，直接返回
  if (isRendering.value) {
    return;
  }

  // 双重验证实例状态
  if (!pdfDoc || typeof pdfDoc.getPage !== 'function') {
    console.error('PDF实例无效，无法渲染页面');
    error.value = true;
    errorMessage.value = 'PDF文档加载不完整，请重试';
    return;
  }

  try {
    isRendering.value = true; // 开始渲染，标记状态

    let page = await pdfDoc.getPage(pageNum);
    const viewport = page.getViewport({scale: scale.value});
    const canvas = pdfCanvas.value;
    const context = canvas.getContext('2d');

    // 清除画布（避免残留上一次渲染内容）
    context.clearRect(0, 0, canvas.width, canvas.height);

    canvas.width = viewport.width;
    canvas.height = viewport.height;

    // 执行渲染并等待完成
    await page.render({canvasContext: context, viewport}).promise;
  } catch (err) {
    console.error('页面渲染错误:', err);
    error.value = true;
    errorMessage.value = `渲染失败: ${err.message}`;
  } finally {
    isRendering.value = false; // 渲染完成，重置状态
  }
};


// 缩放控制方法
const zoomIn = () => {
  if (isRendering.value) return; // 如果正在渲染，不执行新操作
  scale.value += 0.05;
  renderPage(1);
};

const zoomOut = () => {
  if (isRendering.value) return; // 如果正在渲染，不执行新操作
  scale.value -= 0.05;
  renderPage(1);
};


// 下载文件
const downloadFile = () => {
  const fileUrl = currentApplication.value?.companyFiles.fileUrl;
  const fileName = currentApplication.value?.companyFiles.fileName;
  if (!fileUrl) return;

  const link = document.createElement('a');
  link.href = fileUrl;
  link.download = fileName || '未知文件';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 在loadFile中给pdfBlobUrl赋值（替换原URL.createObjectURL行）
// const pdfBlobUrl = URL.createObjectURL(pdfBlob); // 改为：

//监听申请的变化
// watch(
//     () => currentApplication.value,
//     (newVal) => {
//       if (detailDialogVisible.value && newVal) {
//         loadFile();
//       }
//     },
//     {deep: true, immediate: false}
// );

//监听弹窗
watch(
    () => detailDialogVisible.value,
    (visible) => {
      if (!visible) {
        // 清理Blob URL（避免内存泄漏）
        if (pdfBlobUrl) {
          URL.revokeObjectURL(pdfBlobUrl);
          pdfBlobUrl = '';
        }
        // 清理PDF相关状态
        if (pdfDoc) {
          pdfDoc.destroy();  // 释放 PDF 实例资源
          pdfDoc = null;
        }
        canvasRefs.value = {};
        error.value = false;
        isPdf.value = false;
        isRendering.value = false; // 重置渲染状态
      }
    }
);

//监听页面变化
watch(
    () => scale.value,
    () => {
      renderPage(1);
    }
);

</script>

<style scoped>
.rental-approval-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.approval-card {
  margin: 0 auto;
  max-width: 1400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}


.file-previewer {
  width: 100%;
  max-width: 1000px;
  margin: 0 auto;
  padding: 16px;
}

/* 调整内容区域高度 */
:deep(.tall-dialog .el-dialog__body) {
  height: calc(90vh - 120px); /* 总高度减去标题栏和边距 */
  padding: 20px;
  overflow: hidden;
}

.loading {
  text-align: center;
  padding: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.error {
  color: #dc3545;
  padding: 20px;
  text-align: center;
  background-color: #f8d7da;
  border-radius: 4px;
}

.pdf-container {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.toolbar {
  background-color: #f5f5f5;
  padding: 12px 16px;
  border-bottom: 1px solid #e0e0e0;
}

.controls {
  display: flex;
  gap: 20px;
  align-items: center;
  justify-content: center;
  margin-top: 8px;
}

button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.pdf-content {
  padding: 20px;
  text-align: center;
  transition: transform 0.3s ease;
  /* 可选：限制Canvas最大高度，避免超出屏幕 */
  max-height: 80vh;
  overflow-y: auto;
  max-width: none;
}

canvas {
  max-width: 100%; /* 保持自适应容器宽度 */
  max-height: 80vh; /* 最大高度与容器一致 */
  /* 可选：增加阴影让图片更突出 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.non-pdf {
  text-align: center;
  padding: 40px;
  border: 1px dashed #ccc;
  border-radius: 8px;
}

.dialog-footer {
  text-align: center;
  margin-top: 0;
  padding: 16px 0 20px;

  & > .el-button {
    margin-left: 16px;
    min-width: 120px;
  }

  & > .el-button:first-child {
    margin-left: 0;
  }
}

.approval-actions h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}


@media (max-width: 992px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-bar > * {
    width: 100%;
    margin-left: 0 !important;
    margin-bottom: 10px;
  }
}
</style>